package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品和口味
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //自定义方法
        dishService.dishWithFlavor(dishDto);
        //全局清理缓存
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //精确清理缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        //一:基础分页查询
        //分页构造器
        Page<Dish> pageInfo=new Page(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.like(name!=null,Dish::getName,name);
        dlqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
        dishService.page(pageInfo,dlqw);
        //二:完善分页查询
        //创建一个dto分页查询对象
        Page<DishDto>dishDtoPage=new Page<>();

        //拷贝对象数据(排除几何数据,因为确实属性字段)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        //获取不完整的集合数据(dish)对象
        List<Dish> records = pageInfo.getRecords();

        //创建dishDto集合
        List<DishDto> dtoList=new ArrayList<>();

        //遍历dish集合
        records.forEach(dish -> {
            //创建dishDto对象
            DishDto dishDto = new DishDto();
            //获取菜品的id
            Long categoryId = dish.getCategoryId();

            //注入分类service,并通过id查询分类名称
            Category category = categoryService.getById(categoryId);
            //判断category不为空
            if (category!=null){
                //储存分类名称到dishDto
                dishDto.setCategoryName(category.getName());
            }
            //拷贝对象数据
            BeanUtils.copyProperties(dish,dishDto);
            //添加到dtoList集合
            dtoList.add(dishDto);
        });

        //将dishDto集合存入分页对象
        dishDtoPage.setRecords(dtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        //自定义方法
        DishDto dishDto=dishService.getWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品和口味
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //自定义方法
        dishService.updateWithFlavor(dishDto);
        //精确清理缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("修改菜品成功");
    }

    /**
     * 根据菜品分类id查询具体菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getById(Dish dish){
        //创建dishDto集合
        List<DishDto> dtoList=null;
        //动态构建key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //查询缓存数据
         dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //判断数据是否为空
        if (dtoList!=null){
            //不为空返回数据
            return R.success(dtoList);
        }
        //条件构造器
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        //根据菜品分类id
        dlqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //状态在售才显示
        dlqw.eq(Dish::getStatus,1);
        dlqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dlqw);
        //创建dishDto集合
        List<DishDto> dtoList1=new ArrayList<>();
        //遍历dish集合
        list.forEach(dish1 -> {
            //创建dishDto对象
            DishDto dishDto = new DishDto();
            //拷贝对象数据
            BeanUtils.copyProperties(dish1,dishDto);
            //获取菜品的id
            Long dish1Id = dish1.getId();
            //获取菜品口味
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,dish1Id);
            List<DishFlavor> flavors = dishFlavorService.list(lqw);
            dishDto.setFlavors(flavors);
            //添加到dtoList集合
            dtoList1.add(dishDto);
        });
        //储存数据到缓存
        redisTemplate.opsForValue().set(key,dtoList1,60, TimeUnit.MINUTES);
        return R.success(dtoList1);
    }

    /**
     * 删除菜品和口味数据
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.removeWithFlavor(ids);
        //全局清理缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

    /**
     * 菜品起售停售状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long>ids){
        //判断请求状态是停售起售
        if (status==0){
            //判断菜品是否在套餐内
            LambdaQueryWrapper<SetmealDish> slqw = new LambdaQueryWrapper<>();
            slqw.in(SetmealDish::getDishId,ids);
            int count = setmealDishService.count(slqw);
            if (count>0){
               //从查询菜品关系表对象
                List<SetmealDish> list = setmealDishService.list(slqw);
                //创建setmealId集合
                ArrayList<Long> setmealIds = new ArrayList<>();
                list.forEach(setmealDish -> {
                    Long setmealId = setmealDish.getSetmealId();
                    setmealIds.add(setmealId);
                });
                //停售套餐
                LambdaUpdateWrapper<Setmeal> lqw = new LambdaUpdateWrapper<>();
                lqw.in(Setmeal::getId,setmealIds);
                lqw.set(Setmeal::getStatus,status);
                setmealService.update(lqw);
            }
        }

        LambdaUpdateWrapper<Dish> dluw = new LambdaUpdateWrapper<>();
        dluw.in(Dish::getId,ids);
        dluw.set(Dish::getStatus,status);
        dishService.update(dluw);
        //全局清理缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        Set keys1 = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys1);
        return  R.success("修改成功");
    }
}
